# -*- coding: utf-8 -*-
# Author: Lewis
# Date: 2024/3/13

import os

import config
from utils import logger
from openpyxl import load_workbook
from openpyxl_image_loader import SheetImageLoader
from PIL import Image


class ExtractExcel(object):

    def __init__(self, excel_name: str = config.EXCEL_NAME):
        """检查是否存在excel文件， 如果存在则创建保存文件夹"""

        if excel_name in os.listdir():
            self.excel_name = excel_name
            self.__upper_directory = None
        else:
            raise Exception("没有发现此 excel 文件")

    @classmethod
    def extract_from_file(cls, file_path: str, save_file_suffix: str = 'extract') -> bool:
        for file in os.listdir(path=file_path):
            if file.endswith('.xlsx'):
                upper_directory: str = file_path + "_" + save_file_suffix
                if not os.path.exists(upper_directory):
                    os.makedirs(upper_directory)
                cls(excel_name=file).extract_excel_image()

        return True

    def extract_excel_image(self, save_suffix: str = config.SAVE_SUFFIX) -> bool:
        worksheet = load_workbook(self.excel_name).worksheets[config.SHEET_START]
        image_loader = SheetImageLoader(worksheet)
        for index, row in enumerate(worksheet.rows, start=config.DATA_ROW_START):
            img_column = f'{config.COLUMN_IMAGE}{index}'
            if image_loader.image_in(img_column):
                image: Image = image_loader.get(img_column)

                # column_1_title = worksheet.cell(row=index, column=config.COLUMN_INDEX_1).value
                column_1_title = worksheet[f'{config.COLUMN_TEXT_1}{index}'].value
                # 替换字符串中的 * 和 φ
                # column_1_title = column_1_title.replace("*", "X").replace("φ", "-尺寸").replace("/", "-")

                # column_2_title = worksheet.cell(row=index, column=config.COLUMN_INDEX_2).value
                column_2_title = worksheet[f'{config.COLUMN_TEXT_2}{index}'].value
                # 替换字符串中的 * 和 φ
                # column_2_title = column_2_title.replace("*", "X").replace("φ", "-尺寸").replace("/", "-")

                img_name = column_1_title + '_' + column_2_title + ".png"

                excel_directory = self.excel_name.split('.')[0] + "_" + save_suffix
                if not os.path.exists(excel_directory):
                    os.makedirs(excel_directory)
                img_path = f'{excel_directory}/{img_name}'
                try:
                    image.save(img_path)
                except OSError as e:
                    logger.info(msg=f'{self.excel_name} {config.COLUMN_IMAGE}{index} 出现错误：{e}')
                    continue
            else:
                logger.info(msg=f'{self.excel_name} {config.COLUMN_IMAGE}{index} 出现空图片')
        return True
